<?php
class Cms_Model_DAO_Page
{    
	private $_db;
	private static $_instance = null;
	private static $_table = "questions";
 
	/**
	 * @return Cms_Model_DAO_Page
	 * */
	public static function factory() {
		if(self::$_instance == null) {
			self::$_instance = new self();
		}
		
		return self::$_instance;
	}
	
    private function __construct()
    {
    	$module = Utils_Global::get('module');
		$this->_db = Utils_Global::getDbInstance($module);
    }
	
    public function select($options = array()) {
        $sql = "SELECT `a`.`id`, `a`.`last_update`,
		            `t`.`seo_title` `title_seo`, `t`.`content` `title`, `t2`.`content` `content` ";
        $from = " FROM `pages` a INNER JOIN `translation` t ON `a`.`i18n_title` = `t`.`i18n_id` ";
        $from2 = " INNER JOIN `translation` t2 ON `a`.`i18n_content` = `t2`.`i18n_id` ";
        $where = " WHERE `a`.`active` = 1 ";
        
        if(is_array($options)) {
        	if($options['lang']) {
        		$where .= " AND `t`.`lang` = {$this->_db->quote($options['lang'])} AND `t2`.`lang` = {$this->_db->quote($options['lang'])} ";
        	}
        	if($options['id']) {
        	    $where .= " AND `a`.`id` = {$this->_db->quote($options['id'], 'INTEGER')} ";
        	}
        }
        
        $order = " ORDER BY `a`.`last_update` DESC ";
        if($options['order'] && $options['by']) {
        	$order = " ORDER BY `a`.`{$options['order']}` {$options['by']} ";
        }
        
        $limit = "";
        
        if(isset($options['offset']) && $options['offset'] >=0 && $options['limit'] >0) {
        	$limit = " limit {$this->_db->quote($options['offset'], 'INTEGER')}, {$this->_db->quote($options['limit'], 'INTEGER')} ";
        }
        $result = $this->_db->fetchAll ( $sql . $from . $from2 . $where . $order . $limit );
        return $result;
    }
}